/**
 *
 */
package vn.tecviets.thuandt.controller.action.post;

import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import vn.tecviets.thuandt.model.bean.Post;
import vn.tecviets.thuandt.model.bo.PostBO;
import vn.tecviets.thuandt.model.form.LoginActionForm;

/*
 * ReadPostAction
 * 1.0
 * Mar 19, 2013
 * 
 * Copyright notice
 * 
 * Modification Logs:
 * 
 * DATE					AUTHOR				DESCRIPTION
 * -----------------------------------------------------------
 * Mar 19, 2013			Thuandt				Create
 */

public class ReadPostAction extends Action {

	PostBO postBO = new PostBO();

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws ClassNotFoundException, SQLException {
		
//		/*
//		 * Check login session
//		 */
//		LoginActionForm loginActionForm = (LoginActionForm) request.getSession().getAttribute("loginActionForm");
//		if (loginActionForm == null) {
//			return mapping.findForward("login");
//		}
		
		int pageIndex = 1; 		// Store index of page, which user wants to go
		int firstPage = 1;		// Store index of first page
		int lastPage = 1; 		// Store index of last page
		int nextPage = 1; 		// Store index of next page from current page
		int previousPage = 1; 	// Store index of previous page from current page
		
		ArrayList<Post> postArrayList;	// Store all posts in a specific page
		
		try {
			
			int totalPage = postBO.getTotalPage();	// Store quantity of page
			lastPage = totalPage;
			
			/*
			 * Get index of page, which user wants to go
			 */
			if (request.getParameter("page") != null) {
				pageIndex = Integer.parseInt(request.getParameter("page"));
			}

			if (pageIndex > 1) {
				previousPage = pageIndex - 1;
			}

			if (pageIndex < totalPage) {
				nextPage = pageIndex + 1;
			} else {
				nextPage = totalPage;
			}
			
			postArrayList = postBO.getPostForPaging(pageIndex);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		
		request.setAttribute("postArrayList", postArrayList);
		request.setAttribute("firstPage", firstPage);
		request.setAttribute("previousPage", previousPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("lastPage", lastPage);
		
		return mapping.findForward("read");
	}
}
